const BaseController = require('../framework/platform/controller/base_controller.js');
const ProjectModel = require('../config/models_config').project_model;
const timeUtil = require('../framework/helpers/time_util.js');
const appCode = require('../framework/core/app_code.js');
const config = require('../config/config.js');

class ProjectController extends BaseController {
    constructor(app) {
        super(app);
        this._model = new ProjectModel(this);
    }

    /** 获取项目列表 */
    async getProjectList() {
        // 数据校验
        let rules = {
            search: 'string|min:0|max:30|name=搜索条件',
            sortType: 'string|name=搜索类型',
            sortVal: 'name=搜索类型值',
            page: 'must|int|default=1',
            size: 'must|int',
            status: 'string|name=状态',
        };

        // 取得数据
        let input = this.validateData(rules);
        let service = new ProjectModel(this);
        let result = await service.getProjectList(input);

        // 数据格式化
        let list = result.list;
        for (let k = 0; k < list.length; k++) {
            list[k].startDate = timeUtil.timestamp2Time(list[k].startDate, 'Y-M-D');
            list[k].deadline = timeUtil.timestamp2Time(list[k].deadline, 'Y-M-D');
            list[k].createTime = timeUtil.timestamp2Time(list[k].createTime);
        }

        return result;
    }

    /** 获取项目详情 */
    async getProjectDetail() {
        // 数据校验
        let rules = {
            id: 'must|id',
        };

        // 取得数据
        let input = this.validateData(rules);
        let service = new ProjectModel(this);
        let detail = await service.getProjectDetail(input.id);
        if (detail) {
            detail.startDate = timeUtil.timestamp2Time(detail.startDate, 'Y-M-D');
            detail.deadline = timeUtil.timestamp2Time(detail.deadline, 'Y-M-D');
            detail.createTime = timeUtil.timestamp2Time(detail.createTime);
        }

        return detail;
    }

    /** 创建项目 */
    async createProject() {
        // 数据校验
        let rules = {
            // 不再要求name字段
            // name: 'must|string|min:2|max:50|name=项目名称',
            model: 'string|min:2|max:50|name=型号', // 增加model字段
            leader: 'must|string|min:2|max:20|name=项目负责人',
            department: 'must|string|min:2|max:20|name=所属部门',
            startDate: 'must|date|name=开始日期',
            deadline: 'must|date|name=截止日期',
            priority: 'must|string|name=优先级',
            status: 'must|string|name=状态',
            description: 'string|max:500|name=项目描述',
            applicationType: 'string|max:50|name=应用类型',
            workTemp: 'string|max:50|name=工作环境温度',
            certification: 'string|max:100|name=认证要求',
            lowPower: 'string|max:50|name=低功耗要求',
            startupTime: 'string|max:50|name=启动时间要求',
            conformalCoating: 'string|max:10|name=三防漆要求',
            ratedVoltage: 'string|max:50|name=额定电压',
            maxPower: 'string|max:50|name=最大功率',
            maxSpeed: 'string|max:50|name=最高转速'
        };

        // 取得数据
        let input = this.validateData(rules);
        
        // 确保model字段存在
        if (!input.model) {
            input.model = `PRJ-${Date.now().toString().slice(-6)}`;
            console.log('[createProject] 自动生成model字段:', input.model);
        }
        
        // 移除name字段
        if (input.name) {
            console.log('[createProject] 删除name字段，使用model作为标识');
            delete input.name;
        }
        
        input.startDate = timeUtil.time2Timestamp(input.startDate);
        input.deadline = timeUtil.time2Timestamp(input.deadline);

        console.log('[createProject] 验证后的数据:', input);

        // 显式过滤字段，只保留ProjectModel.DB_STRUCTURE中定义的字段
        const filteredInput = {};
        Object.keys(input).forEach(key => {
            if (key in ProjectModel.DB_STRUCTURE) {
                filteredInput[key] = input[key];
            }
        });

        console.log('[createProject] 过滤后的数据:', filteredInput);

        let service = new ProjectModel(this);
        let result = await service.insertProject(filteredInput);

        return result;
    }

    /** 更新项目 */
    async updateProject() {
        // 数据校验
        let rules = {
            id: 'must|id',
            name: 'must|string|min:2|max:50|name=项目名称',
            leader: 'must|string|min:2|max:20|name=项目负责人',
            department: 'must|string|min:2|max:20|name=所属部门',
            startDate: 'must|date|name=开始日期',
            deadline: 'must|date|name=截止日期',
            priority: 'must|string|name=优先级',
            status: 'must|string|name=状态',
            description: 'string|max:500|name=项目描述',
            applicationType: 'string|max:50|name=应用类型',
            workTemp: 'string|max:50|name=工作环境温度',
            certification: 'string|max:100|name=认证要求',
            lowPower: 'string|max:50|name=低功耗要求',
            startupTime: 'string|max:50|name=启动时间要求',
            conformalCoating: 'string|max:10|name=三防漆要求',
            ratedVoltage: 'string|max:50|name=额定电压',
            maxPower: 'string|max:50|name=最大功率',
            maxSpeed: 'string|max:50|name=最高转速'
        };

        // 取得数据
        let input = this.validateData(rules);
        input.startDate = timeUtil.time2Timestamp(input.startDate);
        input.deadline = timeUtil.time2Timestamp(input.deadline);

        let service = new ProjectModel(this);
        let result = await service.updateProject(input);

        return result;
    }

    /** 删除项目 */
    async deleteProject() {
        // 数据校验
        let rules = {
            id: 'must|id',
        };

        // 取得数据
        let input = this.validateData(rules);
        let service = new ProjectModel(this);
        await service.deleteProject(input.id);
    }
} 